//
//  MyAddressViewController.m
//  FD
//
//  Created by Yasin on 2018/10/17.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//

#import "MyManageAddressViewController.h"
//view
#import "MyAddressSectionHeaderView.h"
#import "MyAddressCell.h"
//controller
#import "EditSongCanAddressController.h" //编辑送餐地址
#import "MyAddAddressViewControllerXin.h" //1-8 新增送餐地址

//model
#import "MyAddressModel.h"

@interface MyManageAddressViewController ()<UITableViewDelegate,UITableViewDataSource,
MyAddressCellDelegate>
/**tv*/
@property (nonatomic,  strong) UITableView *tv;
/**数据源*/
@property (nonatomic,  strong) NSMutableArray *dataArr;

@end

@implementation MyManageAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)setupView {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = NSLocalizedString(AddrssManagement, @"配送地址管理");
    //取消导航条线
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
//    [self.navigationController.navigationBar setTranslucent:NO]; //不透明

//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:[UIImage new]];


    self.tv.frame = self.view.bounds;
    [self.view addSubview:self.tv];
    self.tv.tableFooterView = [UIView new];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MyAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyAddressCell"];
    cell.delegate = self;
    
    //设置数据
    cell.model = self.dataArr[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MyAddressSectionHeaderView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MyAddressSectionHeaderView"];
    
    FDWeakSelf;
    sectionHeaderView.myAddressSectionHeaderViewClickAddBlock = ^{
        MyAddAddressViewControllerXin *addAddressVC = [[MyAddAddressViewControllerXin alloc] init];
        addAddressVC.fromWhichVC = 2;
        [weakSelf.navigationController pushViewController:addAddressVC animated:YES];
    };
    
    return sectionHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44 + 10;
}

//删除cell
#pragma mark -  MyAddressCellDelegate
- (void)addressCellClickDeleteAction:(MyAddressCell *)cell {
    //计算下标
    NSIndexPath *indexPath = [self.tv indexPathForCell:cell];
    
    MyAddressModel *model = self.dataArr[indexPath.row];
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(L_Delete, @"删除") message:NSLocalizedString(L_ShiFouShanChuGaiDiZhi, @"是否删除该地址")
 preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(Cancel, @"取消")
 style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:NSLocalizedString(L_Confirm, @"确定") style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

        //删除收货地址
        [self requestRemoveAddrssWithId:model.addressId];
    }];
    
    [alertVC addAction:cancel];
    [alertVC addAction:sure];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

//!!!!:编辑送餐地址
- (void)addressCellClickEditAction:(MyAddressCell *)cell {
    //计算下标
    NSIndexPath *indexPath = [self.tv indexPathForCell:cell];

    //取出对应的modle
    MyAddressModel *currentModel = self.dataArr[indexPath.row];
    EditSongCanAddressController *editVC = [[EditSongCanAddressController alloc] init];
    editVC.addressModel = currentModel;
    editVC.fromWhichVC = 1;
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark - getter
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (UITableView *)tv
{
    if (!_tv) {
        _tv = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        //代理
        _tv.delegate = self;
        _tv.dataSource = self;
        
        //注册cell
        [_tv registerClass:[MyAddressCell class] forCellReuseIdentifier:@"MyAddressCell"];
        
        //注册区头
        [_tv registerClass:[MyAddressSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"MyAddressSectionHeaderView"];
    }
    return _tv;
}

#pragma mark - 请求数据
- (void)loadData {
    [FDHttpAPi requestUserShouHuoAddressSucccessBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) { //请求成功解析数据
            NSArray *data = responseObjc[@"data"];
    
            //清空之前数据
            if (self.dataArr.count) {
                [self.dataArr removeAllObjects];
            }
       
            for (NSDictionary *dic in data) {
                MyAddressModel *model = [MyAddressModel mj_objectWithKeyValues:dic];
                
                [self.dataArr addObject:model];
            }
            
            //刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tv reloadData];
            });
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } fialBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}

//删除收货地址 先别调
- (void)requestRemoveAddrssWithId:(NSNumber *)addressId {
    [FDHttpAPi requestUserAddressRemoveWithID:addressId succesBlock:^(id responseObjc) {
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) { //删除成功
            
            [JRToast showWithText:NSLocalizedString(ToastDeleteSuccess, @"删除成功")];
            //调查请求请求接口，重新获取数据，并刷新表格
            [self loadData];
            
        }else { //toast
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
    }];
}
@end
